package com.ding.second.socket;

import java.util.HashMap;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value = "/talk/{userId}")
public class WebSocket {

	static Map<String, Session> sessionMap = new HashMap<String, Session>();

	@OnOpen
	public void onOpen(Session session, @PathParam(value = "userId") String userId) {
		sessionMap.put(userId, session);
		System.out.println(userId);
	}

	@OnMessage
	public void onMessage(String unscrambledWord, Session session, @PathParam(value = "userId") String userId)
			throws Exception {

		String talkId = unscrambledWord.substring(0, unscrambledWord.indexOf("#"));
		String talkWord = unscrambledWord.substring(unscrambledWord.indexOf("#") + 1);

		Session userSession = sessionMap.get(userId);
		userSession.getBasicRemote().sendText("{type:'" + "message" + "',text:' 我说：" + talkWord + "'}");

		Session talkSession = sessionMap.get(talkId);
		talkSession.getBasicRemote().sendText("{type:'" + "message" + "',text:'" + talkId + "：" + talkWord + "'}");
	}

	@OnClose
	public void onClose() {
	}

	@OnError
	public void onError(Throwable throwable) {
	}

	public static Map<String, Session> getSessionMap() {
		return sessionMap;
	}
	
}
